﻿using System;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;

using BLL;
using Utility;

namespace EvaluationSystem
{
    public partial class QuestionList : System.Web.UI.Page
    {
        private const int Q_MAX_DISPLAY_LENGTH = 30;

        protected void Page_Load(object sender, EventArgs e)
        {
            ((SiteSystemMaster)Master).InitMenu();
            ((SiteSystemMaster)Master).li3.Attributes.Add("class", "hover ccc");
            ((SiteSystemMaster)Master).b_hmenu1.Style.Add("display", "none");
            ((SiteSystemMaster)Master).b_hmenu2.Style.Add("display", "none");
            ((SiteSystemMaster)Master).b_hmenu3.Style.Clear();
            ((SiteSystemMaster)Master).s_menu3_2.Style.Add("COLOR", "#147ab8");
            ((SiteSystemMaster)Master).s_menu3_2.Style.Add("TEXT-DECORATION", "none"); 

            /*判断是否是管理员身份*/
            if (Session["username"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "PopupScript", "<script>alert('请先登录系统!');top.location.href='../System/Login.aspx';</script>");
                return;
            }
            else
            {
                if (!IsPostBack)
                {
                    bind();
                }
            }           
        }

        private void bind()
        {
            DimensionBLL dimensionBll = new DimensionBLL();
            DataSet dsPosition = dimensionBll.GetDimensionAll();
            ddlDimension.DataSource = dsPosition.Tables[0].DefaultView;           
            ddlDimension.DataValueField = "dimension_id";
            ddlDimension.DataTextField = "dimension_name";
            ddlDimension.DataBind();

            if (Request.QueryString["dimID"] != null)
            {
                ddlDimension.SelectedValue = Request.QueryString["dimID"];
            }

            QuestionBLL quesitionBll = new QuestionBLL();
            DataSet ds = quesitionBll.GetQuestionByDimension(ddlDimension.SelectedValue);
            
            grVQuestionManage.DataSource = ds.Tables[0].DefaultView;
            grVQuestionManage.DataSourceID = null;
            grVQuestionManage.DataBind();           

            quesitionBll = null;
            dimensionBll = null;
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            QuestionBLL temp = new  QuestionBLL();
            int selectCount = 0;
            int question_id = 0;
            foreach (GridViewRow gr in grVQuestionManage.Rows)
            {
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                if (chk.Checked)
                {
                    question_id = int.Parse(grVQuestionManage.DataKeys[gr.RowIndex].Values[0].ToString());
                    temp.Delete(question_id);
                    selectCount++;
                }
            }

            if (0 == selectCount)
            {
                //MessageBox.Show("对不起，你没有选择记录!");
            }

            temp = null;
            Response.Redirect(Request.Url.ToString());
        }

        protected void CB_SelectAll_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.grVQuestionManage.Rows.Count; i++)
            {
                GridViewRow gr = this.grVQuestionManage.Rows[i];
                CheckBox chk = (CheckBox)gr.Cells[0].FindControl("CB_Select");
                chk.Checked = this.CB_SelectAll.Checked; //跟随全选按扭的状态变化;
            }
        }       

        protected void btnNew_Click(object sender, EventArgs e)
        {
            //新增题目
            Response.Redirect("~/System/AddQuestion.aspx?dimID="+ddlDimension.SelectedValue);
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            //导出到Excel
            QuestionBLL quesitionBll = new QuestionBLL();
            DataSet ds = quesitionBll.GetQuestionByDimension(ddlDimension.SelectedValue);

            ds.Tables[0].Columns[0].ColumnName = "库内题号";
            
            DataColumn dc = new DataColumn();
            dc.DataType = Type.GetType("System.String");
            dc.ColumnName = "维度名称";
            dc.DefaultValue = ddlDimension.SelectedItem.ToString();

            ds.Tables[0].Columns.Add(dc);
            ds.Tables[0].Columns["维度名称"].SetOrdinal(1);
            ds.Tables[0].Columns[1].DefaultValue = ddlDimension.SelectedItem.ToString();
            ds.Tables[0].Columns.Add("鉴别度", Type.GetType("System.String"));
            ds.Tables[0].Columns["鉴别度"].SetOrdinal(2);
            ds.Tables[0].Columns.Add("难度", Type.GetType("System.String"));
            ds.Tables[0].Columns["难度"].SetOrdinal(3);
            ds.Tables[0].Columns[4].ColumnName = "维度库内编号";
            ds.Tables[0].Columns[5].ColumnName = "题干内容";
            ds.Tables[0].Columns.Add("最后修改时间", Type.GetType("System.DateTime"));
            ds.Tables[0].Columns["最后修改时间"].SetOrdinal(6);
            ds.Tables[0].Columns[7].ColumnName = "选项A内容";
            ds.Tables[0].Columns[8].ColumnName = "选项B内容";
            ds.Tables[0].Columns[9].ColumnName = "选项C内容";
            ds.Tables[0].Columns[10].ColumnName = "选项D内容";
            ds.Tables[0].Columns[11].ColumnName = "选项E内容";
            ds.Tables[0].Columns[12].ColumnName = "选项A分值";
            ds.Tables[0].Columns[13].ColumnName = "选项B分值";
            ds.Tables[0].Columns[14].ColumnName = "选项C分值";
            ds.Tables[0].Columns[15].ColumnName = "选项D分值";
            ds.Tables[0].Columns[16].ColumnName = "选项E分值";
            
            ds.Tables[0].Columns.Remove("question_dimensionid");
            ds.Tables[0].Columns.Remove("question_status");
            ds.Tables[0].Columns.Remove("question_typeid");

            string filePath = Server.MapPath("../userfiles") + @"\question_" + DateTime.Now.ToString("yyyyMMdd_HH_mm_ss") + ".xls";
            string fileName = Path.GetFileName(filePath);
            ExcelLibrary.DataSetHelper.CreateWorkbook(filePath, ds);
            Stream stream = null;
            stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            long bytesToRead = stream.Length;
            Response.Clear();
            Response.ContentType = "application/ms-excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);

            while (bytesToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    byte[] buffer = new Byte[10000];
                    int length = stream.Read(buffer, 0, 10000);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    bytesToRead = bytesToRead - length;
                }
                else
                {
                    bytesToRead = -1;
                }
            }
        }

        protected void ddlDimension_SelectedIndexChanged(object sender, EventArgs e)
        {
            QuestionBLL quesitionBll = new QuestionBLL();
            DataSet ds = quesitionBll.GetQuestionByDimension(ddlDimension.SelectedValue);
            grVQuestionManage.DataSource = ds.Tables[0].DefaultView;
            grVQuestionManage.DataSourceID = null;
            grVQuestionManage.DataBind();
        }

        protected void grVQuestionManage_DataBound(object sender, EventArgs e)
        {
            foreach (GridViewRow gvr in grVQuestionManage.Rows)
            {
                string qTitle = gvr.Cells[3].Text.Trim();//如果题干内容过长，则进行截取。
                if (!string.IsNullOrEmpty(qTitle) && qTitle.Length > Q_MAX_DISPLAY_LENGTH)
                {
                    gvr.Cells[3].Text = qTitle.Substring(0, Q_MAX_DISPLAY_LENGTH) + "...";
                }
            }
        }

        protected void GridView1_IndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grVQuestionManage.PageIndex = e.NewPageIndex;
            QuestionBLL quesitionBll = new QuestionBLL();
            DataSet ds = quesitionBll.GetQuestionAll();
            grVQuestionManage.DataSource = ds.Tables[0].DefaultView;
            grVQuestionManage.DataSourceID = null;
            grVQuestionManage.DataBind();
            quesitionBll  = null;
        }

        protected void GrVQuestionList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int rowIndex = Int32.Parse(e.CommandArgument.ToString());//获取点击了第几行

            if (e.CommandName == "DisableQuestion")
            {
                string strStatus = ((Button)grVQuestionManage.Rows[rowIndex].Cells[6].Controls[0]).Text;
                string questionid = grVQuestionManage.DataKeys[rowIndex].Values[0].ToString();
                QuestionBLL temp = new QuestionBLL();
                switch (strStatus)
                {
                    case "启用":
                        if (temp.UpdateQuestionStatus(questionid, false) != -1)
                        {
                            MessageBox.ShowAndRedirect(this, "已成功开启", "QuestionList.aspx?dimID=" + ddlDimension.SelectedValue);
                        }
                        break;
                    case "禁用":
                        if (temp.UpdateQuestionStatus(questionid, true) != -1)
                        {
                            MessageBox.ShowAndRedirect(this, "已成功禁用", "QuestionList.aspx?dimID=" + ddlDimension.SelectedValue);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }
}